import { Button, Form, Input, Select } from 'antd';
import { useState } from 'react';
import toast from 'react-hot-toast';

type OperationType =
  | 'deposit'
  | 'withdrawal'
  | 'transfer'
  | 'change-password'
  | 'report-loss';

interface CustomerCardOperationProps {
  cardID: string;
  onSuccess: () => void;
}

function CustomerCardOperation({
  cardID,
  onSuccess,
}: CustomerCardOperationProps) {
  const [operation, setOperation] = useState<OperationType>('deposit');
  const onFinish = async (values: any) => {
    const {
      amount,
      password,
      remark,
      targetCardId,
      old_password,
      new_password,
    } = values;
    const apiEndpoints = {
      deposit: 'http://localhost:8000/trades/deposit',
      withdrawal: 'http://localhost:8000/trades/withdraw',
      transfer: 'http://localhost:8000/trades/transfer',
      'change-password': `http://localhost:8000/cards/${cardID}/change-password`,
      'report-loss': `http://localhost:8000/cards/${cardID}/report-loss`,
    };

    const getPayload = () => {
      switch (operation) {
        case 'deposit':
          return { cardID, amount: Number(amount), remark };
        case 'withdrawal':
          return { cardID, amount: Number(amount), password, remark };
        case 'transfer':
          return {
            from_cardID: cardID,
            to_cardID: targetCardId,
            amount: Number(amount),
            password,
            remark,
          };
        case 'change-password':
          return { old_password, new_password };
        case 'report-loss':
          return { password, new_status: true };
      }
    };

    try {
      const response = await fetch(apiEndpoints[operation], {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(getPayload()),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(`${data.detail || '操作成功！'}`);
        onSuccess();
      } else {
        console.log(data);
        toast.error(`${data.detail || '操作失败'}`);
      }
    } catch (error) {
      toast.error(`网络错误: ${error}`);
    }
  };

  const isTradeOperation = ['deposit', 'withdrawal', 'transfer'].includes(
    operation,
  );

  return (
    <Form onFinish={onFinish} layout="vertical">
      <Form.Item label="操作类型">
        <Select value={operation} onChange={setOperation}>
          <Select.Option value="deposit">存款</Select.Option>
          <Select.Option value="withdrawal">取款</Select.Option>
          <Select.Option value="transfer">转账</Select.Option>
          <Select.Option value="change-password">修改密码</Select.Option>
          <Select.Option value="report-loss">挂失</Select.Option>
        </Select>
      </Form.Item>

      {isTradeOperation && (
        <>
          {operation === 'transfer' && (
            <Form.Item
              label="收款卡号"
              name="targetCardId"
              rules={[{ required: true, message: '请输入收款卡号!' }]}
            >
              <Input />
            </Form.Item>
          )}

          <Form.Item
            label={operation === 'transfer' ? '转账金额' : '金额'}
            name="amount"
            rules={[{ required: true, message: '请输入金额!' }]}
          >
            <Input type="number" />
          </Form.Item>
        </>
      )}

      {operation === 'change-password' && (
        <>
          <Form.Item
            label="旧密码"
            name="old_password"
            rules={[{ required: true, message: '请输入旧密码!' }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="新密码"
            name="new_password"
            rules={[{ required: true, message: '请输入新密码!' }]}
          >
            <Input.Password />
          </Form.Item>
        </>
      )}

      {(operation === 'withdrawal' ||
        operation === 'transfer' ||
        operation === 'report-loss') && (
        <Form.Item
          label="银行卡密码"
          name="password"
          rules={[{ required: true, message: '请输入银行卡密码!' }]}
        >
          <Input.Password />
        </Form.Item>
      )}

      {isTradeOperation && (
        <Form.Item label="备注" name="remark">
          <Input.TextArea rows={4} />
        </Form.Item>
      )}

      <Form.Item>
        <Button type="primary" htmlType="submit">
          提交
        </Button>
      </Form.Item>
    </Form>
  );
}

export default CustomerCardOperation;
